<?php

namespace app\api\controller;

use think\Request;
use think\Exception;
use think\facade\Db;
use EasyWeChat\Factory;
use Pimple\Exception\UnknownIdentifierException;
use app\common\model\User;
use tinywan\Jwt;

class AuthController
{
    /**
     * easywechat 5.0 SDK
     */
    public $app;

    public function __construct()
    {
        $config = config('wechat');

        $this->app = Factory::miniProgram($config);
    }
    /**
     * 获取微信小程序手机号
     * @params string
     * @return
     */
    public function getWechatPhone(Request $request)
    {
        $code = $request->post('code');
        try {
            $result = $this->app->phone_number->getUserPhoneNumber($code);
            if($result['errcode'] == 0 && $result['errmsg'] == 'ok')
            {
                $res['phone'] = $result['phone_info']['phone_info'];
                return returnSuccess('ok', $res);
            }else{
                return returnFail('获取手机号失败');
            }
        }catch (Exception $e)
        {
            return returnFail('获取手机号失败');
        }
    }

    /**
     * 微信小程序登录
     * @params string
     * @return
     */
    public function mpLogin(Request $request)
    {
        $code = $request->post('code');

        try {
            //$this->app->auth->session($code);

            $reg['id'] = 1;
            $reg['username'] = '用户_'.get_random_str(4);

            $token = Jwt::generateToken($reg);

            return returnSuccess('ok', ['token'=>$token]);
        }catch (Exception $e)
        {
            return returnFail('微信授权登录失败');
        }
    }

    public function getToken()
    {
        $reg['id'] = 1;
        $reg['username'] = '用户_'.get_random_str(4);

        $token = Jwt::generateToken($reg);

        return returnSuccess('ok', ['token'=>$token]);
    }

    public function test(Request $request)
    {
        return uploadFileCommon($request, 1);
    }

}
